package com.xidian.zhiancloud.controller.myyb;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.SysOrganizationAbandon;
import com.xidian.zhiancloud.service.myyb.OrganizationAbandonService;
import com.xidian.zhiancloud.util.tools.PageUtil;
import com.xidian.zhiancloud.util.tools.Query;
import com.xidian.zhiancloud.util.tools.RequestUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统设置-组织机构
 */
@RestController
@RequestMapping("/organization")
public class OrganizationController {

    private final static Logger logger = LoggerFactory.
            getLogger(OrganizationController.class);

    @Autowired
    private OrganizationAbandonService organizationService;

    /**
     * 组织机构列表
     * @return 组织机构列表
     */
    @GetMapping("/organization_list")
    public ResultDTO selectOrganizationList(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<SysOrganizationAbandon> orgList = organizationService.queryList(query);
        int total = organizationService.queryTotal(query);
        PageUtil pageUtil = new PageUtil(orgList, total, query.getSize(), query.getPage());
        return ResultDTO.successOf(pageUtil,GeneralResponseEnums.SUCCESS);
    }

    /**
     * 删除
     *
     * @param organization 组织机构
     * @return 返回ResultDTO对象
     */
    @GetMapping("/deleteOrganization")
    public ResultDTO<Boolean> deleteOrganization(SysOrganizationAbandon organization) {
        organizationService.deleteById(organization);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 编辑数据
     * @param organization 组织机构对象
     * @return 返回 ResultDTO 对象
     */
    @PatchMapping("/organization_update")
    public ResultDTO<Boolean> updateOrganization(SysOrganizationAbandon organization) {
        organizationService.patchById(organization);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 组织机构添加
     * @param organization 组织机构对象数据
     * @return 返回ResultDTO对象
     */
    @PostMapping("/addOrganization")
    public ResultDTO<Boolean> addOrganization(SysOrganizationAbandon organization) {
        organizationService.add(organization);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 将组织机构导出到excel文件中去
     *
     * @param * 组织机构信息列表
     * @param * 输出表
     * @throws IOException
     */
    @RequestMapping("/exportOrganizationEx")
    public void exportOrganization(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String orgi = "organization";

        String id = RequestUtil.getStringParameter(request, "id", "");//ID
        String departmentName = RequestUtil.getStringParameter(request,
                "departmentName", "");//部门名称
        String organizationType = RequestUtil.getStringParameter(request,
                "organizationType", "");//组织机构类型
        String isSafeDepartment = RequestUtil.getStringParameter(request, "isSafeDepartment", "");//是否为安全机构
        String principalId = RequestUtil.getStringParameter(request, "principalId", "");
        String codes = RequestUtil.getStringParameter(request, "codes", "");
        String phoneNum = RequestUtil.getStringParameter(request, "phoneNum", "");

        Map<String, Object> mapResult = new HashMap<String, Object>();

        mapResult.put("id", id);
        mapResult.put("departmentName", departmentName);
        mapResult.put("organizationType", organizationType);

        mapResult.put("isSafeDepartment", isSafeDepartment);
        mapResult.put("principalId", principalId);
        mapResult.put("codes", codes);
        mapResult.put("phoneNum", phoneNum);

        List<SysOrganizationAbandon> organizationList = null;

        if (StringUtils.isNotEmpty(id) || StringUtils.isNotEmpty(departmentName) ||
                StringUtils.isNotEmpty(organizationType) || StringUtils.isNotEmpty(isSafeDepartment)
                || StringUtils.isNotEmpty(principalId) || StringUtils.isNotEmpty(codes) ||
                StringUtils.isNotEmpty(phoneNum)) {
            organizationList = organizationService.queryList(mapResult);
        }

        //else if(
//                StringUtils.isEmpty(id) && StringUtils.isEmpty(departmentName) &&
//                StringUtils.isEmpty(organizationType) && StringUtils.isEmpty(isSafeDepartment)
//                && StringUtils.isEmpty(principalId) && StringUtils.isEmpty(codes) &&
//                StringUtils.isEmpty(phoneNum)) {
//        organizationList = organizationService.findByOrgiOrderByCreatetimeDesc(orgi);
//        }

        response.reset(); // 必要地清除response中的缓存信息

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        String fileName = "组织机构信息表.xls";

        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            // firefox浏览器
        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            // 谷歌
        }

        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        //07版本以前的Excel文件,即后缀名为.xls,
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("organization");
        HSSFRow row;
        HSSFCell cell;
        String createtime = "";
        String updatetime = "";
        row = sheet.createRow(0);
        String[] titles = {"序号", "部门名称", "组织机构类型", "是否为安全机构 (是?)", "负责人", "编码", "固定电话"};
        for (int i = 0; i < titles.length; i++) { // 创建一个单元格，设置单元格的值
            cell = row.createCell(i);
            cell.setCellValue(titles[i]);
        }
        // 从第1行开始写数据
        for (int i = 0; i < organizationList.size(); i++) {
            // 创建表格的第i+1行
            row = sheet.createRow(i + 1);
            // 写该行的各列数据
            SysOrganizationAbandon organization = organizationList.get(i);
            int j = 0;

            Long organizationType_D = Long.valueOf(organization.getDepartId());//公司机构类型
            int isSafeDepartments = Integer.valueOf(organization.getIsSafeDepartment());//是否是安全机构

            cell = row.createCell(j++);
            cell.setCellValue(i + 1); // 序号
            cell = row.createCell(j++);
            cell.setCellValue(organization.getName());//部门名称
            cell = row.createCell(j++);
            cell.setCellValue
                    (organizationType_D.equals("1") ? "公司级" :
                            (organizationType_D.equals("2")) ? "部门级" :
                                    (organizationType_D.equals("3")) ? "车间级" :
                                            (organizationType_D.equals("4")) ? "班组级" : null);//公司机构类型
            cell = row.createCell(j++);
            cell.setCellValue(organization.getIsSafeDepartment());
            cell = row.createCell(j++);
            cell.setCellValue(isSafeDepartments == 0 ? "不是" : "是");//是否是安全机构 0:不是 ,1:是
            cell = row.createCell(j++);
            cell.setCellValue(organization.getUserid());//负责人
            cell = row.createCell(j++);
            cell.setCellValue(organization.getCodes());//编码
            cell = row.createCell(j++);
            cell.setCellValue(organization.getOfficetel());//电话

        }

        // 将excel的数据写入文件
        javax.servlet.ServletOutputStream os = response.getOutputStream();
        wb.write(os);
        os.close();

    }


}
